package com.woniuxy.yygh.msm.controller;


import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.woniuxy.yygh.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;


/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 验证码
 * <P> Date: 2022/3/4:20:46
 * <P> Description:
 */
@RestController
@RequestMapping("/api/msm")
public class FileController  extends BaseController {

    //图片生成
    @Resource
    public Producer producer;

    @GetMapping("/captcha")
    public Result captcha() throws IOException {

        //验证码存入redis时的key值,用于用户登陆时,再从redis中查找验证码是否正确
        String key = UUID.randomUUID().toString();
        //随机生成的验证码字符
        String code = producer.createText();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());


        //把图片验证验证码的存入redis中, key:为captcha+uudi ,value为:随机生成的字符, 有效时间为2min
        redisUtil.set(key, code, 100);
        //返回base64格式的图片验证码
        return Result.ok(
                MapUtil.builder()
                        .put("token", key)
                        .put("captchaImg", base64Img)
                        .build()

        ).message("获取验证码成功");
    }

}

